<template>
  <div class="goods-add">
    <!-- 面包屑 -->
    <el-row>
      <my-breadcrumb level1="商品管理" level2="商品列表"></my-breadcrumb>
    </el-row>
    <el-row>
      <el-alert
        type="success"
        title="添加商品信息"
        center
        show-icon
        :closable="false"
      ></el-alert>
    </el-row>
    <el-row>
      <el-steps :active="1 * active" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
      </el-steps>
    </el-row>
    <el-row>
      <!-- 将 el-tabs 的所有项给 el-from 包裹，里面每一项数据由它统计 form 管理 -->
      <el-form :model="form" label-width="80px" labelPosition="top">
        <!-- <el-form-item label=""></el-form-item> -->

        <el-tabs
          v-model="active"
          tab-position="left"
          style="height: 450px;"
          @tab-click="handleTabsClick"
        >
          <el-tab-pane label="基本信息" name="1">
            <el-form-item label="商品名称">
              <el-input v-model="form.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格">
              <el-input v-model="form.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量">
              <el-input v-model="form.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量">
              <el-input v-model="form.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <!--级联选择器的使用  -->
              <el-cascader
                :options="categoryData"
                :props="cascaderProps"
                v-model="cascaderSelected"
                @change="handleCategoryChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="2">
            <!-- {{attrsListData}} -->
            <el-alert
              type=""
              title="无参数"
              v-if="attrsManyData.length === 0"
            ></el-alert>
            <el-form-item
              v-for="item in attrsManyData"
              :label="item.attr_name"
              :key="item.attr_id"
            >
              <el-checkbox-group
                v-for="(item1, index1) in item.attr_vals"
                :key="index1"
                v-model="item.attr_vals"
              >
                <el-checkbox :label="item1" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="3">
            <el-alert
              type=""
              title="无属性"
              v-if="attrsOnlyData.length === 0"
            ></el-alert>
            <el-form-item
              v-for="item in attrsOnlyData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals" placeholder=""></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="4">
            <el-form-item label="">
              <el-upload
                class="upload-demo"
                action="http://127.0.0.1:8888/api/private/v1/upload"
                :headers="elUploadHeaders"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="5">
            <el-form-item label="">
              <!-- 表单元素 -->
              <el-button
                type="primary"
                icon="el-icon-circle-plus-outline"
                @click="submitGoodsInfo"
                >添加商品</el-button
              >
              <quill-editor
                :content="form.goods_introduce"
                @change="onEditorChange($event)"
              />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-row>
    <el-dialog title="预览" :visible.sync="imgDialogVisible">
      <img class="preImg" :src="preImgUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import MyBreadcrumb from '@/components/MyBreadcrumb'
export default {
  components: {
    MyBreadcrumb
  },
  props: {},

  data() {
    return {
      active: '1',
      categoryData: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name'
      },
      cascaderSelected: [1, 3, 6],
      attrsManyData: [],
      attrsOnlyData: [],
      checkList: [],
      elUploadHeaders: {},
      form: {
        goods_name: '',
        goods_cat: '1, 3, 6',
        goods_price: '',
        goods_number: '',
        goods_weight: '',
        goods_introduce: '',
        pics: [],
        attrs: []
      },
      imgDialogVisible: false,
      preImgUrl: ''
    }
  },
  created() {
    this.getCategoryData()
    // 给图片上传添加权限
    const token = window.sessionStorage.getItem('token')
    // 请求头加上token
    this.elUploadHeaders.Authorization = token
  },
  methods: {
    // 获取分类列表
    async getCategoryData() {
      const { data } = await this.$http.get('/categories')

      if (data.meta.status === 200) {
        this.categoryData = data.data
      } else {
        this.$message.warning(data.meta.msg)
      }
    },
    // 获取动态参数
    async getManyAttrsListData() {
      const { data } = await this.$http.get(
        `/categories/${this.cascaderSelected[2]}/attributes?sel=many`
      )

      if (data.meta.status === 200) {
        this.attrsManyData = data.data
        // 逗号分隔的字符串，转换为数组
        this.attrsManyData.forEach(item => {
          item.attr_vals =
            // item.attr_vals.length !== 0 ? item.attr_vals.trim().split(',') : []
            item.attr_vals.length !== 0 ? item.attr_vals.trim().split(',') : []
        })
      } else {
        this.$message.warning(data.meta.msg)
      }
    },
    // 获取静态参数
    async getOnlyAttrsListData() {
      const { data } = await this.$http.get(
        `/categories/${this.cascaderSelected[2]}/attributes?sel=only`
      )

      if (data.meta.status === 200) {
        this.attrsOnlyData = data.data
      } else {
        this.$message.warning(data.meta.msg)
      }
    },
    // 分类选择器变动后设置 form 值
    handleCategoryChange(val) {
      this.form.goods_cat = val.join()
    },
    // 点击tab
    handleTabsClick(val) {
      // 如果点击第二个 tab，要求同时 三级分类要有值
      // console.log(val.index)

      if (val.index === '1') {
        if (this.cascaderSelected.length === 0) {
          this.$message.warning('请先选择商品分类')
          return
        }
        this.getManyAttrsListData()
      }

      if (val.index === '2') {
        if (this.cascaderSelected.length === 0) {
          this.$message.warning('请先选择商品分类')
          return
        }
        this.getOnlyAttrsListData()
      }
    },
    // 图片上传的相关方法
    // file 形参，当前操作的图片的相关信息（文件名，路径）
    handlePreview(data) {
      this.imgDialogVisible = true
      this.preImgUrl = data.response.data.url
    },
    handleRemove(data) {
      console.log('handleRemove')
      // 要移除的图片路径
      // data.response.data.tmp_path
      const filePath = data.response.data.tmp_path
      const index = this.form.pics.indexOf(filePath)
      this.form.pics.splice(index, 1)
    },
    handleSuccess(data) {
      console.log('handleSuccess')
      console.log(data)
      this.form.pics.push({
        pic: data.data.tmp_path
      })
    },
    // 获取编辑器内容
    onEditorChange(event) {
      // console.log(event)
    },
    async submitGoodsInfo() {
      console.log('submit')

      // 处理数据
      // 级联选择器数组变字符串
      this.form.goods_cat = this.cascaderSelected.join(',')

      // 动态静态属性
      const attrsManyData = this.attrsManyData.map(item => {
        return {
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        }
      })
      const attrsOnlyData = this.attrsOnlyData.map(item => {
        return {
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        }
      })
      this.form.attrs = [...attrsOnlyData, ...attrsManyData]

      const { data } = await this.$http.post('goods', this.form)

      if (data.meta.status === 201) {
        this.$message.success(data.meta.msg)
        this.$router.push('/goods')
      } else {
        this.$message.warning(data.meta.msg)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.goods-add {
  .el-row {
    padding: 5px 0;
  }
  .el-tabs {
    .el-tab-pane {
      height: 450px;
      overflow: auto;
    }
  }
  .el-step__title {
    font-size: 12px;
  }

  .preImg {
    width: 100%;
  }
}
</style>
